#!/usr/bin/python
"""
Takes all the alt*.txt files
Reporojects the final rasters and outputs colorized tif (*_color.vrt) and data (*._wgs84.tif)
Run from the wgs84 location, final_matt mapset
"""
import os
import sys

import glob
mods = [x.replace('.txt','') for x in glob.glob('alt_*.txt')] 
overall_min = 100
overall_max = 0 
run_proj = True

if run_proj:
    for mod in mods:
        cmd = "g.region -d" 
        print os.popen(cmd).readlines()
       
        cmd = "g.remove rast=%s_wgs84" % mod
        print os.popen(cmd).readlines()

        cmd = "r.proj input=%s_final output=%s_wgs84 location=ca_c mapset=final_matt dbase=/home/perry/grass method=bilinear" % (mod,mod)
        print os.popen(cmd).readlines()


        cmd = "g.region rast=%s_wgs84" % mod
        print os.popen(cmd).readlines()

        cmd = "r.univar %s_wgs84" % mod
        min = None
        max = None
        for line in os.popen(cmd).readlines():
            if line.startswith('minimum'):
                min = float(line.split()[-1]) 
            if line.startswith('maximum'):
                max = float(line.split()[-1]) 

        if min and min < overall_min:
            overall_min = min

        if max and max > overall_max:
            overall_max = max

    if overall_max > 18:
        print
        print "======================"
        print "WARNING  - one of the layers exceeds 18 - revise color ramp"
        print "======================"
        print

for mod in mods:
    cmd = "cat ramp.txt | r.colors map=%s_wgs84 color=rules" % mod
    print os.popen(cmd).readlines()

    cmd = "rm out/%s_color.*" % mod
    print os.popen(cmd).readlines()

    cmd = "r.out.tiff -t input=%s_wgs84 output=out/%s_color" % (mod,mod)
    print os.popen(cmd).readlines()

    cmd = "gdal_translate -a_nodata 255 -a_srs epsg:4326 -of VRT out/%s_color.tif out/%s_color.vrt" % (mod,mod)
    print os.popen(cmd).readlines()

    cmd = "r.out.gdal input=%s_wgs84 output=out/%s_wgs84.tif format=GTiff type=Float32" % (mod,mod)
    print os.popen(cmd).readlines()


